import { SUCCESS_CODE } from '@/utils/typings.d';
import type { RequestData } from '@ant-design/pro-table';
import { message } from 'antd';
import { request } from 'umi';
import { createSearchType, SearchType, searchTypeList, updateSearchType } from './data';

/**
 * 获取物流列表
 * @param params
 */
export async function logisticsSearchPages(
  params: SearchType,
): Promise<RequestData<searchTypeList>> {
  try {
    const res = await request(`/api/logistics/v1.0.0/search/list`, {
      params: {
        ...params,
        page: params.page,
        pageSize: params.pageSize,
      },
    });
    if (!res || res.code !== SUCCESS_CODE) {
      message.error('获取失败');
      return { success: false, total: 0, data: [] };
    }
    const sumlist = () =>
      res.data.map((e: any) => {
        return {
          ...e,
          weightPrice: e.weightPrice.map((item: number) => {
            return Math.round(item);
          }),
        };
      });
    return { code: res.code, message: res.message, data: sumlist(), total: res.total };
  } catch (error) {
    return { code: 1, message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员', data: [] };
  }
}
// 查询物流搜索详情
export async function logisticsSearchDetail(
  id: string,
): Promise<{ success: boolean; data?: any; message: string; code: number }> {
  try {
    const res = await request(`/api/logistics/v1.0.0/search/list/${id}`, {});

    if (!res || res.code !== SUCCESS_CODE) {
      message.error('获取失败');
      return res;
    }
    return res;
  } catch (error) {
    return {
      success: false,
      data: undefined,
      message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员',
      code: 1,
    };
  }
}

// 添加物流
export async function addLogisticsSearch(
  params: createSearchType,
): Promise<{ success: boolean; message: string; code: number }> {
  try {
    const res = await request(`/api/logistics/v1.0.0/search/addList`, {
      method: 'POST',
      data: { ...params },
    });
    if (!res || res.code !== SUCCESS_CODE) {
      return res;
    }
    return res;
  } catch (error) {
    return {
      code: 1,
      success: false,
      message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员',
    };
  }
}

// 更新搜索
export async function updateLogisticsSearch(
  params: updateSearchType,
): Promise<{ success: boolean; message: string; code: number }> {
  try {
    const res = await request(`/api/logistics/v1.0.0/search/updateList`, {
      method: 'POST',
      data: { ...params },
    });
    if (!res || res.code !== SUCCESS_CODE) {
      return res;
    }
    return res;
  } catch (error) {
    return {
      code: 1,
      success: false,
      message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员',
    };
  }
}

// 删除配置
export async function handleLogisticsSearch(id: string) {
  try {
    const res = await request(`/api/logistics/v1.0.0/search/delete/${id}`, {
      method: 'DELETE',
    });
    return res;
  } catch (error) {
    return { code: 1, message: '服务器请求失败，请重试，如果多次请求失败，请联系管理员', data: [] };
  }
}
